<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Ucenter  extends Base_Controller
{
    private $user_id;

    private  $page_limit = 4;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('userv2info_model');
        $this->load->model('userv2_model');
        $this->load->model('apporder_model');
        $this->load->model('userv2mobile_model');
        $this->load->library('Myusersubscribe');
        $this->load->library('MySms');
        $this->load->helper('captcha');
        $this->user_id = 1;
        session_start();
    }
    
    public function checklogin(){
    	if(!isset($_SESSION)){
    		session_start();
    	}
    	if(!isset($_SESSION['is_login'])||$_SESSION['is_login'] != 1) 
    	{$this->success(array('is_login'=>0,"user_type"=>'',"uid"=>''));}
    	else{$this->success(array("is_login"=>1,"user_type"=>$_SESSION['user_type'],"uid"=>$_SESSION['uid']));}
    }

    /**
     * 游客注册
     */
    public function userreg()
    {
        $password = isset($_POST['password']) && strlen($_POST['password'])? $_POST['password'] : null;
        $re_password = isset($_POST['re_password']) && strlen($_POST['re_password'])? $_POST['re_password'] : null;
        if($re_password != $password) $this->error('两次密码输入的不一样');
        //邮箱注册
        if(isset($_POST['way']) && $_POST['way'] == 'email'){
            $email = isset($_POST['email']) && strlen($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : null;
            if($email === null) $this->error('邮箱格式不正确');
            
            $securimage_code_value = isset($_POST['securimage_code_value']) && strlen($_POST['securimage_code_value'])? $_POST['securimage_code_value'] : null;
            $status=check_securimage_code_value($securimage_code_value);
            if($status==2) $this->error('验证码已过期,请重试');
            if($status==3) $this->error('验证码错误');
    
            if($this->userv2_model->getUserv2(array('userId' => $email))) $this->error('该邮箱已被注册');

            $data = array(
                'source'     => 'WAP',
                'userId'     => $email,
                'email'     => $email,
                'userName'   => '新用户',
                'userToken'  => md5($password),
                'userIcon'   => '/resource/skin/img/index_mingxing.png',
                'userGender' => NULL,
            	//免去web端验证邮箱这一步
            	'active'     =>1,
                'status'     => 1,
                'created'    => time(),
                'changed'    => time(),
                'utype'      => 'TOURIST',
            );
            $uid = $this->userv2_model->createUser($data);
            if($uid > 0){
                //$mail_data = $this->myusersubscribe->user_activation($uid,$email,$data['created'],$mail_type='tourist');
                $this->userv2info_model->createUserV2Info(array('uid' => $uid));
                //$status = $mail_data['status'];
                //if(!$status){
                //    $this->error('注册错误，请重试');
                //}else{
                //    $this->success(array('url' => $mail_data['url']));
                //}
            }else{
                $this->error('注册错误，请重试');
            }
        }
        //电话注册
        elseif(isset($_POST['way']) && $_POST['way'] == 'mobile'){
            $phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? $_POST['phoneNum'] : null;
            $areaCode = isset($_POST['areaCode']) && strlen($_POST['areaCode']) ? ltrim($_POST['areaCode'], '+') : null;
            //手机验证码
            $securimage_code_value = isset($_POST['securimage_code_value']) && strlen($_POST['securimage_code_value'])? $_POST['securimage_code_value'] : null;
            $smsCode = $this->userv2mobile_model->getSmsCode(array('mobile' => '+'.$areaCode.$phone));
            if(!$smsCode['status']){
            	$this->error($msg);
            }else {
            	if($smsCode['code'] != $securimage_code_value) $this->error('验证码不正确');
     
            }
            
            if($this->userv2_model->getUserv2(array('telNum' => $phone))) $this->error('该手机号已经注册过');
            
            $data = array(
                'source'     => 'WAP',
                'telNum'     => $phone,
                'userName'   => '新用户',
                'userToken'  => md5($password),
                'userIcon'   => '/resource/skin/img/index_mingxing.png',
                'userGender' => NULL,
                'status'     => 1,
                'telActive'  => 1,
                'active'     => 1,
                'created'    => time(),
                'changed'    => time(),
                'telCode'    => $areaCode,//没有+号
                'utype'      => 'TOURIST',
            );
            $uid = $this->userv2_model->createUser($data);
            if($uid > 0){
                $this->userv2info_model->createUserV2Info(array('uid' => $uid, 'userPhone' => "+".$areaCode.trim($phone)));
                $this->success();
            }else{
                $this->error('注册错误，请重试');
            }
        }
        else {$this->error('注册错误，请重试');}
    }

    /**
     * 玩伴注册
     */
    public function guiderreg()
    {
        $password = isset($_POST['password']) && strlen($_POST['password'])? $_POST['password'] : null;
        $re_password = isset($_POST['re_password']) && strlen($_POST['re_password'])? $_POST['re_password'] : null;
        if($re_password != $password) $this->error('两次密码输入的不一样');
        //邮箱验证
        $email = isset($_POST['email']) && strlen($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : null;
        if($this->userv2_model->getUserv2(array('userId' => $email))) $this->error('该邮箱已经注册过');
        //电话验证
        $phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? $_POST['phoneNum'] : null;
        $areaCode = isset($_POST['areaCode']) && strlen($_POST['areaCode']) ? ltrim($_POST['areaCode'], '+') : null;
        if($this->userv2_model->getUserv2(array('telNum' => $phone))) $this->error('该手机号已经注册过');
        //电话验证码
        $securimage_code_value = isset($_POST['securimage_code_value']) && strlen($_POST['securimage_code_value'])? $_POST['securimage_code_value'] : null;
        $smsCode = $this->userv2mobile_model->getSmsCode(array('mobile' => '+'.$areaCode.$phone));
        if(!$smsCode['status']){
        	$this->error($msg);
        }else {
        	if($smsCode['code'] != $securimage_code_value) $this->error('验证码不正确');
        	 
        }
        //基本信息验证
        $userFamily = isset($_POST['xing']) && strlen($_POST['xing'])? $_POST['xing'] : null;
        $userName = isset($_POST['ming']) && strlen($_POST['ming'])? $_POST['ming'] : null;
        if(!$userFamily || !$userName) $this->error('姓名不能为空');
        $userGender = isset($_POST['sex']) && strlen($_POST['sex'])? $_POST['sex'] : null;        
        if(!$userGender) $this->error('性别不能为空');

        $data = array(
            'source'     => 'WAP',
            'userId'     => $email,
            'userToken'  => md5($password),
            'userName' => $userFamily.$userName,
            'userGender' => $userGender,
            'userIcon'   => '/resource/skin/img/index_mingxing.png',
            'telNum'     => $phone,
            'telCode'    => $areaCode,
            'telActive'  => 1,
            'status'     => 1,
        	'active'     => 1,
            'created'    => time(),
            'changed'    => time(),
            'utype'      => 'GUIDER',
        );
        $uid = $this->userv2_model->createUser($data);
        if($uid > 0){
            //$mail_data = $this->myusersubscribe->user_activation($uid,$email,$data['created'],$mail_type='guider');
            $this->userv2info_model->createUserV2Info(array('uid' => $uid,
            		'userGender'=>$userGender, 'userFamily'=>$userFamily,
            		'userName'=>$userName, 'userPhone' => "+".$areaCode.trim($phone)));
            //$status = $mail_data['status'];
            //if(!$status){
            //    $this->error('注册错误，请重试');
            //}else{
            //    $this->success(array('url' => $mail_data['url']));
            //}
        }else{
            $this->error('注册错误，请重试');
        }
    }

    /**
     * 登录
     */
    public function login()
    {
        $uType = isset($_POST['utype']) && strlen($_POST['utype']) ? strtoupper($_POST['utype']) : 'TOURIST';
		$uType = strtoupper($uType);
		//$phone代表手机或是邮箱
        $phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? $_POST['phoneNum'] : null;
        $password = isset($_POST['password']) && strlen($_POST['password'])? $_POST['password'] : null;
        if(!$phone) $this->error('邮箱或手机号不能为空！');
        if(!$password) $this->error('密码不能为空！');
        
        $res = $this->userv2_model->checkUser($phone,$password,$uType);
        if($res['status']){
            if(!isset($_SESSION)) session_start();
            $_SESSION['uid'] = $res['uid'];
            $_SESSION['user_type'] = $res['utype'];
            $_SESSION['is_login'] = 1;
            //创建login缓存
            $this->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));
            $cache_id = 'login_'.$res['uid'];
            $data=array('uid'=>$res['uid'],'user_type'=>$res['utype'],'is_login'=>1,'login_time'=>time());
            $this->cache->save($cache_id,$data,7200);
            
            $this->success($res['msg']);
        }else{
            $this->error($res['msg']);
        }
    }
    /**
     * 从微信客户端进行微信登陆
     */
    public function showsession(){
    	if(!isset($_SESSION)) session_start();
    	$this->success($_SESSION);
    }
    public function weixinlogin()
    {
    	if(isset($_GET["page"]) && !empty($_GET["page"])){
    		$config['redirect_uri']='http://api.wayatrip.com/ucenter/weixinlogincallback?page='.$_GET["page"];
    	}else{
    		$config['redirect_uri']='http://api.wayatrip.com/ucenter/weixinlogincallback';
    	}
    	
    	$config['scope']='snsapi_base';
    	$this->load->library('openlogin/wechat',$config);
    	//跳转到引导页，静默授权
    	$this->wechat->get_code();	
    }
    //第一次登陆
    public function firstweixinlogin($page = "")
    {
    	$redirect_uri='http://api.wayatrip.com/ucenter/firstlogincallback?page='.$page;    	    	
    	$scope='snsapi_userinfo';
    	$this->wechat->set_scope($scope);
    	$this->wechat->set_redirect_uri($redirect_uri);
    	//跳转到引导页，授权登陆
    	$this->wechat->get_code();
    }
    
    public function weixinlogincallback()
    {
    	if(isset($_GET["page"]) && !empty($_GET["page"])){
    		$page = $_GET["page"];
    	}else{
    		$page = "";
    	}
    	//获取openid
    	$this->load->library('openlogin/wechat');
    	$this->wechat->get_access_token();
    	$openid=$this->wechat->get_openid();
    	//检查用户是否已经注册
    	$res=$this->userv2_model->getUserv2(array('openid'=>$openid),'uid,utype');
    	if(!empty($res)){
    		//设置登陆session
    		if(!isset($_SESSION)) session_start();
    		$_SESSION['uid'] = $res['uid'];
    		$_SESSION['user_type'] = $res['utype'];
    		$_SESSION['is_login'] = 1;
    		$_SESSION['openid'] = $openid;
    		
    		header("Location: http://m.wayatrip.com/".$page);
    		exit;
    	}
    	//没有注册，获取用户基本信息
    	else{
    		$this->firstweixinlogin($page);
    	}
    }
    
    public function firstlogincallback()
    {
    	if(isset($_GET["page"]) && !empty($_GET["page"])){
    		$page = $_GET["page"];
    	}else{
    		$page = "";
    	}
    	
    	$this->load->library('openlogin/wechat');
    	$this->wechat->get_access_token();
    	$info=$this->wechat->get_user_info();
    	//检查用户是否已经注册
    	$res=$this->userv2_model->getUserv2(array('unionid'=>$info['unionid']),'uid,utype');
    	    	
    	if($info!==false && empty($res)){
    		//新用户注册
    		$data = array(
                'source'     => 'wechat',
                'openid'     => $info['openid'],
                'unionid'    => $info['unionid'],
                'userName'   => $info['nickname'],
                'userToken'  => $info['access_token'],
                'userIcon'   => $info['userIcon'],
                'userGender' => $info['gender'],
            	//免去web端验证邮箱这一步
            	'active'     => 1,
                'status'     => 1,
                'created'    => time(),
                'changed'    => time(),
                'utype'      => 'TOURIST',
            );
    		$uid = $this->userv2_model->createUser($data);
    		if($uid > 0){
    			$this->userv2info_model->createUserV2Info(array('uid' => $uid, 'userIcon'=>$info['userIcon'], 'userGender'=>$info['gender']));    		
    			//设置登陆session
    			if(!isset($_SESSION)) session_start();
    			$_SESSION['uid'] = $uid;
    			$_SESSION['user_type'] = 'TOURIST';
    			$_SESSION['is_login'] = 1;
    			$_SESSION['openid'] = $info['openid'];
    			header("Location: http://m.wayatrip.com/".$page);
    			exit;
    		}else{
    			echo "系统发生错误，请重试";
    			exit;
    		}    	    
    	}else{exit;}
    } 
    /**
     * 退出
     */
    public function logout()
    {
        if(!isset($_SESSION)) session_start();
		$uid=$_SESSION['uid'];
		$_SESSION['uid'] = '';
        $_SESSION['user_type'] = '';
        $_SESSION['is_login'] = '';
        unset($_SESSION);
        //删除login缓存
        $this->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));
        $cache_id = 'login_'.$uid;
        $this->cache->delete($cache_id);

        $this->success();
    }

    /**
     * 验证token
     */
    public function confirm_token()
    {
        $token = isset($_GET['token']) && strlen($_GET['token']) ? $_GET['token'] : null;
        if($token == null) $this->error('token 不能为空');
        list($status, $msg) = $this->myusersubscribe->confirm_token($token);
        if($status == 1){
            $this->success();
        }elseif($status == 2){
            $this->error($msg);
        }else{
            $this->error($msg);
        }
    }

    /**
     * 验证码
     */
    public function checkcode()
    {

        $vals = array(
            'word'       => rand(1000, 10000),
			'img_path'  => './captcha/',
			'img_url'   => 'http://www.wayatrip.com/waya_api/captcha/',
            'word_length'=> 4,
			'img_width'  => '80',
            'img_height' => '30',
            'expiration' => 7200
		);
		$ret=create_captcha($vals);
        $this->success($ret);
    }
    /**
	 * 获取电话区号
	 */
	//$code格式为：86，没有+
	public function phone_area_code()
	{
		$this->db->from("phone_area_code");

		if(isset($_GET['areaCode'])){
			$this->db->where("areaCode",$_GET['areaCode']);
		}

		$query = $this->db->get()->result_array();

		$this->success($query);
	}
    /**
     * 发送短信
     */
    public function sendmsg(){
        //$utype = isset($_POST['utype']) && strlen($_POST['utype']) ? $_POST['utype'] : null;
        $phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? trim($_POST['phoneNum']) : null;
        $areacode = isset($_POST['areaCode']) && strlen($_POST['areaCode']) ? $_POST['areaCode'] : null;
        if(!$phone) $this->error('电话号码不能为空');
        if(!$areacode) $this->error('区域号不能为空');
        if($areacode=='86')
        {$area='CN';}
        else {$area='FOREIGN';}
        //生成验证码存入数据库
        $code = mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9);
        $data['mobile'] = '+'.$areacode.$phone;
        $data['code'] = $code;
        $data['created'] = time();
        //控制发送间隔在1分钟以上
        $smsCode = $this->userv2mobile_model->getSmscode(array('mobile' => '+'.$areacode.$phone));
        if($smsCode && ($smsCode['created']+60) >= time()) $this->error('短信发送时间还未过一分钟，请稍后再发！');
        $id = $this->userv2mobile_model->addSmsCode($data);

        if($id>0){
            if($area=="CN"){
                $tpl_id = 1330065;
                $tpl_value = "#code#={$code}";
                $rs = $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, '+'.$areacode.$phone);
            }else{
                $tpl_id = 1129805;
                $tpl_value = "#code#={$code}";
                $rs = $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, '+'.$areacode.$phone);
            }
            $rs = json_decode($rs,true);
            if($rs['code'] == 0){
               $this->success('短信发送成功');
            }
        }
        $this->error('发送失败请重试');

    }

}
